﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using HtmlAgilityPack;
using log4net;
using WatiN.Core;

namespace PlayerStat
{
    public class ScrapeESPN : ScrapeSite
    {
        ILog logger;
        WebClient wc = new WebClient();
        private int leagueID = -1;
        private string match_url_template = @"http://soccernet.espn.go.com/scores?date={0}&league={1}&cc=4716";
        private string match_stat_url_template = @"http://soccernet.espn.go.com/match?id={0}&cc=4716";
        //private string player_stat_url_template = @"http://soccernet.espn.go.com/gamecast/statistics?id={0}&cc=4716";
        private string league = string.Empty;

        public ScrapeESPN()
        {
            logger = LogManager.GetLogger("scrape");

            if (logger == null)
            {
                throw new Exception("Null Logger");
            }
        }

        public void SetLeague(int nLeagueID)
        {
            leagueID = nLeagueID;
            switch (leagueID)
            {
                case 1:
                    league = "eng.1";
                    return;
                case 2:
                    league = "eng.2";
                    return;
                case 3:
                    league = "eng.3";
                    return;
                case 4:
                    league = "eng.4";
                    return;
                case 5:
                    league = "eng.5";
                    return;
                case 6:
                    league = "ita.1";
                    return;
                case 7:
                    league = "esp.1";
                    return;
                default:
                    throw new Exception("Wrong League Number");
            }
        }

        public bool Scrape()
        {
            logger.Debug("#Scrape ESPN# Start");

            HtmlDocument mainDoc = new HtmlDocument();
            HtmlDocument statDoc = new HtmlDocument();

            try
            {
                EventInit evnt = new EventInit(leagueID);
                string date = string.Empty;

                while (evnt.GetEventDate(leagueID, out date))
                {
                    logger.DebugFormat("Date is {0}", date);
                    string url = string.Format(match_url_template, new string[] { date, league });

                    logger.Debug("Download match list.");
                    //mainIE.GoTo(url);
                    wc.DownloadFile(url, @"C:\Scrape\MainIE.html");
                    logger.Debug("Goto match list.");
                    mainDoc.Load(@"C:\Scrape\MainIE.html",Encoding.GetEncoding("ISO-8859-1"));
                    //System.Threading.Thread.Sleep(5 * 1000);
                    logger.Debug("Start to find gamebox");
                    
                    HtmlNodeCollection gambox = mainDoc.DocumentNode.SelectNodes("//div[@class='gamebox']");
                    
                    if (gambox == null)
                    {
                        //No match today
                        continue;
                    }
                    
                    foreach (HtmlNode divNode in gambox)
                    {
                        HtmlNode listNode = divNode.SelectSingleNode(".//ul[@class='teams']");
                        if (listNode != null && listNode.ChildNodes.Count == 4)
                        {
                            MatchData md = new MatchData();
                            md.LeagueID = leagueID;
                            md.home = listNode.SelectSingleNode("./li[2]/a").InnerText;
                            md.away = listNode.SelectSingleNode("./li[4]/a").InnerText;
                            md.match.homeScore = -1;
                            md.match.awayScore = -1;
                            if (listNode.SelectSingleNode("./li[1]").InnerText.Equals("Postp"))
                            {
                                logger.DebugFormat("Match({0} : {1}) is postponed.", new string[] { md.home, md.away });
                            }
                            else
                            {
                                if (GetScore(listNode.SelectSingleNode("./li[3]").InnerText, ref md.match.homeScore, ref md.match.awayScore))
                                {
                                    logger.DebugFormat("Scrape the match({0} : {1} ) data.", new string[] { md.home, md.away });
                                    //statIE = new IE();
                                    //get the match id
                                    string id = divNode.Id.Replace("-gamebox", "");//link.Url.Substring(link.Url.LastIndexOf(@"id/"));

                                    //match statistic
                                    url = string.Format(match_stat_url_template, id);
                                    logger.Debug("Download match statistic page.");
                                    //statIE.GoTo(url);
                                    wc.DownloadFile(url, @"C:\Scrape\StatIE.html");
                                    logger.Debug("Goto match statistic page.");
                                    statDoc.Load(@"C:\Scrape\StatIE.html", Encoding.GetEncoding("ISO-8859-1"));
                                    //System.Threading.Thread.Sleep(1000 * 2);

                                    logger.Debug("Get match time.");
                                    if (!GetMatchTime(statDoc, ref md.matchTime))
                                    {
                                        logger.Error("Failed to parse match time");
                                        //statIE.Close();
                                        return false;
                                    }
                                    if (md.ExistInDB())
                                    {
                                        md = null;
                                        logger.DebugFormat("Data is already scraped into DB.");
                                        continue;
                                    }
                                    md.homeplayers = new Dictionary<int, PlayerStat>();
                                    md.awayplayers = new Dictionary<int, PlayerStat>();
                                    logger.Debug("Get match details infomation.");
                                    if (!GetMatchDetails(statDoc, ref md.match, ref md.homeplayers, ref md.awayplayers))
                                    {
                                        logger.Error("Failed to parse match statistic page.");
                                        //statIE.Close();
                                        return false;
                                    }
                                    //player mark statistic
                                    //url = string.Format(player_stat_url_template, id);
                                    //logger.Debug("Goto player marking page.");
                                    //statIE.GoTo(url);

                                    //logger.Debug("Get players' marking.");
                                    //if (!GetPlayerMarkStat(statIE, ref md.homeplayers, ref md.awayplayers))
                                    //{
                                    //    logger.Error("Failed to parse player statistic page.");
                                    //    statIE.Close();
                                    //    return false;
                                    //}
                                    //System.Threading.Thread.Sleep(1000 * 2);
                                    //statIE.Close();
                                    //statDoc = null;
                                }
                                else
                                {
                                    logger.Debug("Failed to parse match score");
                                    return false;
                                }
                                logger.Debug("Save match to DB.");
                                md.SaveToDB();
                            }
                        }
                        else
                        {
                            logger.Debug("Teams Div is not existed or imcompleted.");
                        }
                    }
                    //Sleep 5 sec
                    //System.Threading.Thread.Sleep(1000 * 5);
                }
                logger.Debug("#Scrape ESPN# End");
                return true;
            }
            catch (Exception ex)
            {
                logger.Error("#Scrape ESPN# Failed: Exception.");
                logger.Error(ex.ToString());
                return false;
            }
            finally
            {
                logger.Debug("#Scrape ESPN# Finally");
                wc.Dispose();
                if (statDoc != null)
                {
                    logger.Debug("#Scrape ESPN# Close StatIE");
                    statDoc = null;
                }
                if (mainDoc != null)
                {
                    logger.Debug("#Scrape ESPN# Close MainIE");
                    mainDoc = null;
                }

            }
        }

        //Get the match time from the match statistic page
        public bool GetMatchTime(HtmlDocument doc, ref DateTime dt)
        {
            try
            {
                HtmlNode divNode = doc.DocumentNode.SelectSingleNode(".//div[@class='game-time-location']");
                if (divNode != null)
                {
                    foreach (HtmlNode p in divNode.ChildNodes)
                    {
                        try
                        {
                            dt = DateTime.Parse(p.InnerText);
                            return true;
                        }
                        catch (Exception ex1)
                        {
                            continue;
                        }
                    }
                    return false;
                }
                else
                {
                    logger.Error("#GetMatchTime# Failed: game-time-location is not found.");
                    return false;
                }
            }
            catch (Exception ex)
            {
                logger.Error("#GetMatchTime# Failed: Exception.");
                logger.Error(ex.ToString());
                return false;
            }
        }

        //Get the cards number from the match statistic page
        public bool GetCards(IE ie, string id,  ref int homeYellow, ref int homeRed, ref int awayYellow, ref int awayRed)
        {
            try
            {
                //get yellow card number
                TableRow tr = ie.TableRow(Find.ById(id + "Yellow"));
                logger.Debug("#GetCards# Get yellow card number.");
                if (tr.Exists && tr.TableCells.Count == 3)
                {
                    homeYellow = int.Parse(tr.TableCells[0].Text);
                    awayYellow = int.Parse(tr.TableCells[2].Text);
                }
                else
                {
                    homeYellow = -1;
                    awayYellow = -1;
                    logger.Error("#GetCards# Failed: Yellow card is not found.");
                    return false;
                }
                //get red card number
                tr = ie.TableRow(Find.ById(id + "Red"));
                logger.Debug("#GetCards# Get red card number.");
                if (tr.Exists && tr.TableCells.Count == 3)
                {
                    homeRed = int.Parse(tr.TableCells[0].Text);
                    awayRed = int.Parse(tr.TableCells[2].Text);
                }
                else
                {
                    homeYellow = -1;
                    awayYellow = -1;
                    logger.Error("#GetCards# Failed: Red card is not found.");
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                homeYellow = -1;
                awayYellow = -1;
                logger.Error("#GetCards# Failed Exception");
                logger.Error(ex.ToString());
                return false;
            }
        }

        //Get the cards number from the match statistic page
        public bool GetMatchDetails(HtmlDocument doc, ref MatchStat match, ref Dictionary<int, PlayerStat> homeplayers, ref Dictionary<int, PlayerStat> awayplayers)
        {
            try
            {   
                HtmlNodeCollection tables = doc.DocumentNode.SelectNodes("//table[@class='mod-data']");
                if (tables.Count == 12)
                {                    
                    //if (!GetMatchStat(tables.ElementAt(1), ref match))
                    //{
                    //    logger.Error("Failed to parse match statistic.");
                    //    return false;
                    //}
                    //get home team players
                    if (!GetPlayer(tables.ElementAt(2), ref homeplayers))
                    {
                        logger.Error("Failed to parse home team players(top).");
                        return false;
                    }
                    //if (!GetPlayer(tables.ElementAt(3),true, ref homeplayers))
                    //{
                    //    logger.Error("Failed to parse home team players(bench).");
                    //    return false;
                    //}
                    //get away team players
                    if (!GetPlayer(tables.ElementAt(7), ref awayplayers))
                    {
                        logger.Error("Failed to parse away team players(top).");
                        return false;
                    }
                    //if (!GetPlayer( tables.ElementAt(8), true, ref awayplayers))
                    //{
                    //    logger.Error("Failed to parse away team players(bench).");
                    //    return false;
                    //}
                    //set goal minute statistic
                    if (!GetGoalStat(tables.ElementAt(0), ref homeplayers, ref awayplayers))
                    {
                        logger.Error("Failed to parse goal statistic.");
                        return false;
                    }
                    //set yellow card statistic of home team
                    if (!GetCardMin(tables.ElementAt(5), false,ref match.homeYCard, ref homeplayers))
                    {
                        logger.Error("Failed to parse home's yellow card statistic.");
                        return false;
                    }
                    //set red card statistic of home team
                    if (!GetCardMin(tables.ElementAt(6), true, ref match.homeRCard, ref homeplayers))
                    {
                        logger.Error("Failed to parse red's yellow card statistic.");
                        return false;
                    }
                    //set yellow card statistic of away team
                    if (!GetCardMin(tables.ElementAt(10), false, ref match.awayYCard, ref awayplayers))
                    {
                        logger.Error("Failed to parse away's yellow card statistic.");
                        return false;
                    }
                    //set red cad statistic of away team
                    if (!GetCardMin(tables.ElementAt(11), true, ref match.awayRCard, ref awayplayers))
                    {
                        logger.Error("Failed to parse away's red card statistic.");
                        return false;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                return false;
            }
        }
        
        //Get the goal's statistic in the match statistic page
        public bool GetGoalStat(HtmlNode table, ref Dictionary<int,PlayerStat> homeplayers,ref Dictionary<int,PlayerStat> awayplayers)
        {
            if (homeplayers == null || homeplayers.Count == 0 || awayplayers == null || awayplayers.Count == 0)
            {
                logger.Error("#GetGoalStat# Failed: Player data is empty.");
                return false;
            }
            try
            {
                HtmlNode tbody = table.SelectSingleNode("./tbody");
                if (tbody == null)
                {
                    throw new Exception("Un-recognized goal table");
                }
                HtmlNodeCollection rows = tbody.SelectNodes("./tr");
                if (rows == null)
                {
                    //no score
                    return true;
                }
                foreach (HtmlNode tr in rows)
                {
                    MinuteStat stat;
                    if (!tr.ChildNodes[0].InnerText.Trim().Equals("&nbsp;") && tr.ChildNodes[0].InnerText.IndexOf("miss") == -1)
                    {
                        stat = new MinuteStat();
                        if (!ParseMinuteData(tr.ChildNodes[0], true, ref stat))
                        {
                            logger.Error("#GetGoalStat# Failed: Failed to parse goal cell.");
                            return false;
                        }
                        else
                        {
                            if (stat.isOwnGoal)
                            {
                                if (!GetGoalMin(stat, ref awayplayers))
                                {
                                    logger.Error("#GetGoalStat# Failed: Failed to get own goal minute data.(1)");
                                    return false;
                                }
                            }
                            else
                            {
                                if (!GetGoalMin(stat, ref homeplayers)) 
                                {
                                    logger.Error("#GetGoalStat# Failed: Failed to get goal minute data.(2)");
                                    return false;
                                }
                            }
                        }
                    }
                    if (!tr.ChildNodes[1].InnerText.Trim().Equals("&nbsp;") && tr.ChildNodes[1].InnerText.IndexOf("miss") == -1)
                    {
                        stat = new MinuteStat();
                        if (!ParseMinuteData(tr.ChildNodes[1], true, ref stat))
                        {
                            logger.Error("#GetGoalStat# Failed: Failed to parse goal cell.");
                            return false;
                        }
                        else
                        {
                            if (stat.isOwnGoal)
                            {
                                if (!GetGoalMin(stat, ref homeplayers))
                                {
                                    logger.Error("#GetGoalStat# Failed: Failed to get own goal minute data.(3)");
                                    return false;
                                }
                            }
                            else
                            {
                                if (!GetGoalMin(stat, ref awayplayers))
                                {
                                    logger.Error("#GetGoalStat# Failed: Failed to get goal minute data.(4)");
                                    return false;
                                }
                            }
                        }
                    }
                }

                return true;
            }
            catch (Exception ex)
            {
                logger.Error("#GetGoalStat# Failed: Exception.");
                logger.Error(ex.ToString());
                return false;
            }
        }
        
        //Set Goal data to player
        public bool GetGoalMin(MinuteStat stat, ref Dictionary<int, PlayerStat> players)
        {
            var result = from p in players.Values
                         where p.playerName == stat.name
                         select p;
            if (result.Count() == 0)
            {
                logger.ErrorFormat("#GetGoalMin# Failed: Player ({0}) is not found when set goal dada", stat.name);
                return false;
            }
            else
            {
                PlayerStat player = result.ElementAt(0);
                player.MinStat.Add(stat);
                //player.isOwnGoal = stat.isOwnGoal;
                //player.goalMin = stat.goalMin;
                if (stat.isOwnGoal)
                {
                    player.owngoal = player.owngoal + 1;
                }
                else
                {
                    //Own goal should not be counted
                    player.goal = player.goal + 1;
                }
                return true;
            }
        }
        
        //Set the yellow/red card statistic in the match statis page
        public bool GetCardMin(HtmlNode table, bool redcard, ref int count, ref Dictionary<int, PlayerStat> players)
        {
            try
            {
                if (players == null || players.Count == 0)
                {
                    logger.Error("#GetCardMin#Failed: Player data is empty");
                    return false;
                }
                if (table.SelectNodes("./tr[1]/td").Count == 1)
                {
                    // no yellow/red cards
                    return true;
                }
                count = 0;
                HtmlNodeCollection rows = table.SelectNodes("./tr");
                if (rows == null)
                {
                    // no data
                    return true;
                }
                foreach (HtmlNode tr in rows)
                {
                    string min = tr.ChildNodes[0].InnerText;
                    min = min.Replace("'", "").Trim();
                    string name = tr.ChildNodes[1].InnerText;
                    var result = from p in players.Values
                                 where p.playerName == name
                                 select p;
                    if (result.Count() == 0)
                    {
                        logger.ErrorFormat("#GetCardMin#Failed: Player ({0})is not found when set yellow/red card", name);
                        return false;
                    }
                    else
                    {
                        PlayerStat player = result.ElementAt(0);
                        if (redcard)
                        {
                            player.rCardMin = int.Parse(min);
                        }
                        else
                        {
                            player.yCardMin1 = int.Parse(min);
                        }
                        count = count + 1;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                logger.Error("#GetCardMin#Failed: Exception");
                logger.Error(ex.ToString());
                return false;
            }
        }
        
        //Get the match statistic in the match statistic page
        public bool GetMatchStat(Table table, ref MatchStat match)
        {
            try
            {
                if (table.TableRows.Count != 8)
                {
                    logger.Debug("#GetMatchStat#Warnning: Match statistic data is incomplete");
                }
                for (int i = 0; i < table.TableRows.Count; i++)
                {
                    TableRow tr = table.TableRows[i];
                    string home = tr.TableCells[0].Text.Trim();
                    string away = tr.TableCells[2].Text.Trim();
                    switch (i)
                    {
                        case 0://Shot Data
                            logger.Debug("#GetMatchStat# Shot Data.");
                            string homeg = home.Substring(home.IndexOf('(') + 1);
                            string awayg = away.Substring(home.IndexOf('(') + 1);
                            homeg = homeg.Remove(homeg.IndexOf(')'));
                            home = home.Remove(home.IndexOf('('));
                            awayg = awayg.Remove(awayg.IndexOf(')'));
                            away = away.Remove(away.IndexOf('('));
                            int.TryParse(home, out match.homeShot);
                            int.TryParse(homeg, out match.homeShotg);
                            int.TryParse(away, out match.awayShot);
                            int.TryParse(awayg, out match.awayShotg);
                            break;
                        case 1://Fouls Data
                            logger.Debug("#GetMatchStat# Fouls Data.");
                            int.TryParse(home, out match.homeFouls);
                            int.TryParse(away, out match.awayFouls);
                            break;
                        case 2://Conner Kicks Data
                            logger.Debug("#GetMatchStat# Conner Kicks Data.");
                            int.TryParse(home, out match.homeCorner);
                            int.TryParse(away, out match.awayConrner);
                            break;
                        case 3://Offsides Data
                            logger.Debug("#GetMatchStat# Offsides Data.");
                            int.TryParse(home, out match.homeOffsides);
                            int.TryParse(away, out match.awayOffsides);
                            break;
                        case 4://Possession Data
                            logger.Debug("#GetMatchStat# Possession Data.");
                            home = home.Replace("%","");
                            away = away.Replace("%","");
                            int.TryParse(home, out match.homePossession);
                            int.TryParse(away, out match.awayPossession);
                            break;
                        case 5://Yellow Card Data
                            logger.Debug("#GetMatchStat# Yellow Card Data.");
                            int.TryParse(home, out match.homeYCard);
                            int.TryParse(away, out match.awayYCard);
                            break;
                        case 6://Red Card Data
                            logger.Debug("#GetMatchStat# Red Card Data.");
                            int.TryParse(home, out match.homeRCard);
                            int.TryParse(away, out match.awayRCard);
                            break;
                        case 7://Save Data
                            logger.Debug("#GetMatchStat# Save Data.");
                            int.TryParse(home, out match.homeSave);
                            int.TryParse(away, out match.awaySave);
                            break;
                    }       
                }
                return true;
            }
            catch (Exception ex)
            {
                logger.Error("#GetMatchStat#Failed: Exception.");
                logger.Error(ex.ToString());
                return false;
            }
        }
        
        //Get the player list in the match statistic page
        public bool GetPlayer(HtmlNode table, ref Dictionary<int, PlayerStat> players)
        {
            try
            {
                PlayerStat player;
                int number;
                bool isSub;
                HtmlNodeCollection trNodes = table.SelectNodes("./tr");
                for (int i = 0; trNodes!= null && i < trNodes.Count; i++)
                {
                    HtmlNode tr = trNodes.ElementAt(i);
                    number = int.Parse(tr.ChildNodes[0].InnerText.Trim());
                    player = new PlayerStat();
                    player.playerName = tr.ChildNodes[1].SelectSingleNode("./span[1]/a").InnerText;
                    try
                    {
                        string tempstr = tr.ChildNodes[1].SelectSingleNode("./span[@class='statLineSpan']").Id.Replace("statLine", "");
                        player.playerID = int.Parse(tempstr.Trim());
                    }
                    catch (Exception ex)
                    {
                        logger.ErrorFormat("Failed to parse player ID. {0}", player.playerName);
                        logger.Error(ex.ToString());
                        player.playerID = -1;
                    }
                    player.isPlayerSub = IsSubstitution(tr);
                    player.isSwitchOut = IsSwitchOut(tr);
                    player.markID = Marking.GetMarkingID(player.isPlayerSub, player.isSwitchOut);
                    player.posID = PlayerPos.ParsePosID(tr.ChildNodes[2].InnerText);
                    if (players.ContainsKey(number))
                    {
                        logger.WarnFormat("Player({0}) is in the list will be replaced by player({1})", players[number].playerName,player.playerName);
                        players[number] = player;
                    }
                    else
                    {
                        players.Add(number, player);
                    }
                    //}
                }
                return true;
            }
            catch (Exception ex)
            {
                logger.Error("#GetPlayer# Failed: Exception.");
                logger.Error(ex.ToString());
                return false;
            }
        }
        
        public bool IsSubstitution(HtmlNode tr)
        {
            //soccer-icons soccer-icons-subin
            HtmlNode div = tr.SelectSingleNode("./div[@class='soccer-icons soccer-icons-subin']");
            if (div != null)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        
        public bool IsSwitchOut(HtmlNode tr)
        {
            //soccer-icons soccer-icons-subout
            HtmlNode div = tr.SelectSingleNode("./div[@class='soccer-icons soccer-icons-subout']");
            if (div != null)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        
        //Parse the minute data
        public bool ParseMinuteData(HtmlNode cell, bool goalflag, ref MinuteStat stat)
        {
            try
            {
                stat.name = cell.SelectSingleNode("./a[1]").InnerText;
                string str = cell.InnerText.Remove(0,stat.name.Length).Trim().Substring(1);
                str = str.Replace("')", "").Trim();
                if (goalflag)
                {
                    //parse goal miniute data
                    if (str.IndexOf("og") != -1)
                    {
                        stat.isOwnGoal = true;
                        str = str.Replace("og", "");
                    }
                    else
                    {
                        stat.isOwnGoal = false;
                    }
                    str = str.Replace("pen", "");
                    stat.goalMin = int.Parse(str.Trim());
                }
                else
                {
                    //parse cars,substitutes data
                    stat.goalMin = int.Parse(str);
                }
                
                return true;
            }
            catch (Exception ex)
            {
                logger.Error("#ParseMinuteData#Failed: Exception");
                logger.Error(ex.ToString());
                return false;
            }
        }
        
        //Get the score from <gamebox> in the match list page
        public bool GetScore(string str, ref int homescore, ref int awayscore)
        {
            string[] strs = str.Replace("&nbsp;", " ").Split(' ');
            if (strs != null && strs.Length == 3)
            {
                try
                {
                    homescore = int.Parse(strs[0]);
                    awayscore = int.Parse(strs[2]);
                    return true;
                }
                catch (Exception ex)
                {
                    logger.Error("#GetScore# Failed: Exception.");
                    homescore = -1;
                    awayscore = -1;
                    return false;
                }
            }
            else
            {
                if (str.IndexOf('-') != -1)
                {
                    strs = str.Replace("&nbsp;", "").Split('-');
                }
                else if (str.IndexOf('a') != -1)
                {
                    strs = str.Replace("&nbsp;", "").Split('a');
                }
                else
                {
                    logger.ErrorFormat("#GetScore# Failed: Unkonw score {0}",str);
                    homescore = -1;
                    awayscore = -1;
                    return false;
                }
                try
                {
                    homescore = int.Parse(strs[0]);
                    awayscore = int.Parse(strs[1]);
                    return true;
                }
                catch (Exception ex)
                {
                    logger.Error("#GetScore# Failed: Exception.");
                    homescore = -1;
                    awayscore = -1;
                    return false;
                }
            }
        }

        //Get the marks from player statistic page
        public bool GetPlayerMarkStat(IE ie, ref Dictionary<int, PlayerStat> homeplayers, ref Dictionary<int, PlayerStat> awayplayers)
        {
            if (homeplayers == null || homeplayers.Count == 0 || awayplayers == null || awayplayers.Count == 0)
            {
                logger.Error("#GetGoalStat# Failed: Player data is empty.");
                return false;
            }
            try
            {
                Div homeDiv = ie.Div(Find.ById("homeTeamPlayerStats"));
                if (!homeDiv.Exists)
                {
                    logger.Error("#GetPlayerMarkStat# Failed: Failed to home team's data.");
                    return false;
                }
                Div awayDiv = ie.Div(Find.ById("awayTeamPlayerStats"));
                if (!awayDiv.Exists)
                {
                    logger.Error("#GetPlayerMarkStat# Failed: Failed to away team's data.");
                    return false;
                }
                if (!GetMarks(homeDiv, ref homeplayers))
                {
                    logger.Error("#GetPlayerMarkStat# Failed: Failed to get home players' mark.");
                    return false;
                }
                if (!GetMarks(awayDiv,ref awayplayers))
                {
                    logger.Error("#GetPlayerMarkStat# Failed: Failed to get home players' mark.");
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                logger.Error("#GetPlayerMark# Failed: Exception.");
                logger.Error(ex.ToString());
                return false;
            }
        }
        
        //Get marks data
        public bool GetMarks(Div div, ref Dictionary<int, PlayerStat> players)
        {
            try
            {
                Table table = div.Table(Find.ByClass("tablehead"));
                foreach (TableRow tr in table.TableBodies[0].TableRows)
                {

                }
                return true;
            }
            catch (Exception ex)
            {
                logger.Error("#GetMarks# Failed: Exception.");
                logger.Error(ex.ToString());
                return false;
            }
        }
    }
}
